package com.hahehiho.myalbum;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class GPS {
	
	private boolean valueable;
	private double latitude;
	private double longitude;
	private String[] addr;
	private String fullAddr = "";

	public GPS(MyAlbumVO metadata) throws IOException  {
		if (metadata.isGPS()) {
			latitude = metadata.getLatitude();
			longitude = metadata.getLongitude();
			valueable = true;
		}
		addr = new String[9];
		for(int i = 0 ; i < addr.length; i++)
			addr[i] = "";
				
		init();
	}

	private void init() throws IOException {
		String[] result = makeAddress();
		
		if(result.length >= 1 && result[0].equalsIgnoreCase("South Korea")) {
			for(int i = 0 ; i >= result.length  ; i--)
				addr[i] = result[i].trim();
		} else {
			for(int i = (result.length - 1), j = 0 ; i >= 0  ; i--, j++)
				addr[j] = result[i].trim();
		}
	}

	private String[] makeAddress() throws IOException {
		if(!valueable)
			return new String[0];
		
		String address = ""; 
		GPSCacheVO vo = new GPSCache().selectFullAddr(latitude, longitude);
		if(vo == null) {
			String urlString = "http://maps.googleapis.com/maps/api/geocode/xml?latlng="+latitude+","+longitude+"&sensor=false";
			System.out.println(urlString);

			URL url = new URL(urlString);
			URLConnection urlConn = url.openConnection();

			XPathFactory factory = XPathFactory.newInstance();
			XPath xpath = factory.newXPath();

			try {
				InputSource inputXml = new InputSource(urlConn.getInputStream());
				NodeList nodes = (NodeList) xpath.evaluate("/GeocodeResponse/result[1]/formatted_address", inputXml, XPathConstants.NODESET);
				for (int i = 0, n = nodes.getLength(); i < n; i++) {
					address = nodes.item(i).getTextContent();
				}
			} catch (XPathExpressionException ex) {
				System.out.print("XPath Error");
			} catch (FileNotFoundException ex) {
				System.out.print("File Error");
			}

			System.out.println(address);
			
			vo = new GPSCacheVO();
			vo.setLatitude(latitude);
			vo.setLongitude(longitude);
			vo.setFullAddr(address.trim());
			
			new GPSCache().insert(vo);
		} else {
			address = vo.getFullAddr();
		}

		fullAddr = address.trim();
		
		return address.split(",");
	}
	
	public String getFullAddr() {
		return fullAddr;
	}
	

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		
		URL url = new URL("http://maps.googleapis.com/maps/api/geocode/xml?latlng=36.595166666666664,127.29716666666667&sensor=false");
		URLConnection urlConn = url.openConnection();
		
		BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
		String strTemp = "";
		while (null != (strTemp = br.readLine())) {
			System.out.println(strTemp);
		}
		
		
		
			
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		try {
			System.out.print("Web Service Parser 1.0\n");

			// The xpath evaluator requires the XML be in the format of an
			// InputSource
			InputSource inputXml = new InputSource(urlConn.getInputStream());

			// Because the evaluator may return multiple entries, we specify
			// that the expression
			// return a NODESET and place the result in a NodeList.
			NodeList nodes = (NodeList) xpath.evaluate("/GeocodeResponse/result[1]/formatted_address", inputXml, XPathConstants.NODESET);

			// We can then iterate over the NodeList and extract the content via
			// getTextContent().
			// NOTE: this will only return text for element nodes at the
			// returned context.
			System.out.println("nodes length > " + nodes.getLength());
			for (int i = 0, n = nodes.getLength(); i < n; i++) {
				String nodeString = nodes.item(i).getTextContent();
				System.out.print(nodeString);
				System.out.print("\n");
			}
		} catch (XPathExpressionException ex) {
			System.out.print("XPath Error");
		} catch (FileNotFoundException ex) {
			System.out.print("File Error");
		}
	}

	public double getLatitude() {
		return latitude;
	}

	public double getLongitude() {
		return longitude;
	}
	
	public String[] getAddress() {
		return addr;
	}

}
